#!/bin/bash

#------------------------------------------------------------------------------
#   NOTE: Put the following into cron
#      30 3 * * * /usr/local/bin/mysql_backup.sh
#
#   ACKNOWLEDGEMENTS:
#      HTTPS://web.archive.org/web/20180510035437/http://www.linuxbrigade.com/back-up-all-of-your-mysql-databases-nightly/
#------------------------------------------------------------------------------

PathToGnusocial=${1:-""}
BackupPath=./backups/
StampVersion=`date -u +"%Y%m%dT%H%M%SZ"`
BackupDir="${BackupPath}${StampVersion}"
Hostname=`hostname | awk -F. '{print $1}'`

# Echo back
echo ${PathToGnusocial}
echo ${BackupDir}
echo ${Hostname}

# Create the backup directory
mkdir -p $BackupDir

# Prompt for input
read -p "DB_NAME:" DB_NAME
read -p "DB_USER:" DB_USER

mysqldump --user=$DB_USER --password --events --opt --single-transaction $DB_NAME \
    | gzip > "$BackupDir/mysqldump.gz"

if [ "$?" -eq 0 ]
then
    echo "Success"
else
    echo "Mysqldump encountered a problem look in database.err for information"
fi
echo "Done with database."

# Now backup the file and avatar directories
#     as well as the .htaccess and config.php
tar -c ${PathToGnusocial}avatar/ \
    ${PathToGnusocial}file/ \
    ${PathToGnusocial}.htaccess \
    ${PathToGnusocial}config.php \
    | gzip > "$BackupDir/files.gz"
echo "Done with files."
